package com.sun.mvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
public class ScopeController {


    ///////////////////////////////////// 向域中共享数据 request域、session域、applicationContext域 begin ///////////////////////////////
    //1、使用ServletAPI向request域对象共享数据
    @RequestMapping(value = {"testScopeByServlet"})
    public String testScopeByServlet(HttpServletRequest request){
        request.setAttribute("testScope_HttpServletRequest", "hello servlet request");
        return "success";
    }

    //2、使用ModelAndView向request域对象共享数据
    @RequestMapping(value = {"/testModelAndView"})
    public ModelAndView testModelAndView(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("testScope_ModelAndView", "hello , ModelAndView");
        modelAndView.setViewName("success");
        return modelAndView;
    }

    //3、使用Model向request域对象共享数据
    @RequestMapping(value = {"/testModel"})
    public String testModel(Model model){
        model.addAttribute("testScope_Model", "hello model");
        return "success";
    }

    //4、使用map向request域对象共享数据
    @RequestMapping(value = {"/testMap"})
    public String testMap(Map<String ,Object> map){
        map.put("testScope_Map", "hello map");
        map.put("testScope_Map1", "hello map1");
        return "success";
    }

    //5、使用ModelMap向request域对象共享数据
    @RequestMapping("/testModelMap")
    public String testModelMap(ModelMap modelMap){
        modelMap.addAttribute("testScope_ModeMap", "hello,ModelMap");
        return "success";
    }

    //7、向session域共享数据
    @RequestMapping(value = {"/testSession"})
    public String testSession(HttpSession session){
        session.setAttribute("testSessionScope", "hello , session");
        return "success";
    }

    //8、向application域共享数据
    @RequestMapping(value = {"/testApplication"})
    public String testApplication(HttpSession session){
        ServletContext application = session.getServletContext();
        application.setAttribute("testApplicationScope", "hello application");
        return "success";
    }
}
